<?php

namespace app\api\Service;

use app\common\library\Auth;
use think\Db;
use think\Config;

class ShareService
{
    // 邀请二维码
    public static function getUserShare($data){
        $auth = Auth::instance();
        $invite_code = $auth->invite;

        $appid = Config::get('site.miniapp_id');
        $appsecret = Config::get('site.miniapp_secret');
        $access_token = self::accessToken($appid, $appsecret);

        $width = 450;//二维码宽度
        $page = 'pages/index/index';//小程序路径(pages/index/index)
        $scene = "pid={$invite_code}";//携带的参数（?id=1&tag=2）

//        $wx_api = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";// 圆码
        $wx_api = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$access_token";// 方码

        $data = [
            'path'      => $page.'?'.$scene,
            'width'     => $width,
        ];

        $post_data  = json_encode($data);

        $result     = self::api_notice_increment($wx_api, $post_data);     //获取微信小程序二维码

        $tmp = json_decode($result,true);
        if(isset($tmp['errcode'])){
            return (['code' => 401, 'msg' => $tmp['errmsg']]);
        }else{
            $filename = 'uid_'.$auth->id.'.jpg';

            $dir = ROOT_PATH.'public/share';
            if(!is_dir($dir)){
                @mkdir($dir,0777,true);
            }

            $file = $dir.'/'.$filename;
            file_put_contents($file,$result);
            $retFile =request()->domain().'/share/'.$filename;
            return (['code' => 200, 'msg' => '获取成功','data'=>['url'=>$retFile,'invite_code'=>$invite_code]]);
        }
    }

    // 获取邀请列表
    public static function getShareList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit']) ? $data['limit'] : 10;

        $list = Db::name('user')->where('pid', $user_id)->order('createtime desc')->field('id')->paginate($limit)->each(
            function($item){
                $userInfo = \app\admin\model\User::where(['id'=>$item['id']])->field('id,nickname,avatar,createtime')
                    ->find();
                if($userInfo) {
                    $item['nickname'] = $userInfo['nickname'];
                    $item['avatar'] = $userInfo['avatar'] ? $userInfo['avatar'] : request()->domain().'/assets/img/avatar.png';
                    $item['createtime_text'] = date('Y-m-d H:i:s', $userInfo['createtime']);
                }
                return $item;
            }
        );
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }







    // 获取AccessToken
    private static function accessToken($APP_ID, $SECRET)
    {
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $APP_ID . "&secret=" . $SECRET;
        $res = file_get_contents($token_access_url);
        $result = json_decode($res, true);
        $access_token = $result['access_token'];
        return $access_token;
    }

    // 获取微信小程序二维码
    private static function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = array("Accept-Charset: utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            // var_dump($tmpInfo);
            return $tmpInfo;
        }
    }
}